package com.delayqueue.common.netty;

import io.netty.channel.ChannelHandlerContext;
import lombok.Getter;
import lombok.Setter;

import java.util.Objects;

@Setter
@Getter
public class Node {

    private String ip;
    private int port;
    private int connectPort;
    private ChannelHandlerContext channelHandlerContext;

    public Node() {

    }

    public Node(Address address) {
        this.ip = address.getIp();
        this.port = address.getPort();
    }

    public Node(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    public String name() {
        return ip + ":" + port;
    }

    @Override
    public boolean equals(Object o) {
        if (ip == null) {
            return false;
        }
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Node master = (Node) o;
        return port == master.port && ip.equals(master.ip);
    }

    @Override
    public int hashCode() {
        return Objects.hash(ip, port);
    }


    public void release() {
        if (channelHandlerContext != null) {
            channelHandlerContext.channel().close();
            channelHandlerContext.close();
        }
    }
}
